package com.thyrsus.project.controller.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.thyrsus.project.form.search.SearchForm;
import com.thyrsus.project.form.user.UserForm;
import com.thyrsus.project.helper.Constants;
import com.thyrsus.project.helper.SessionHelper;
import com.thyrsus.project.helper.URLHelper;
import com.thyrsus.project.helper.UserHelper;
import com.thyrsus.project.service.user.UserService;

@Controller
@SessionAttributes
public class SearchUserController {
	
	static Logger LOGGER = Logger.getLogger(SearchUserController.class);

	@Autowired
	UserService userService;
	
	/**
	 * If the user look up in his history it will redirect the user to the right page
	 * And launch a real search
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/user/search")
    public String doSearch(HttpServletRequest request,HttpServletResponse response) {
		return "redirect:/home/"+Constants.SEARCH_TAB_INDEX;
	}
	
	/**
	 * Launch the research
	 * @param searchForm
	 * @param result
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/user/search", method = RequestMethod.POST)
    public ModelAndView doSearch(@ModelAttribute("searchForm")
                            SearchForm searchForm, BindingResult result, HttpServletRequest request,HttpServletResponse response) {
		if (!UserHelper.isConnected(request)) {
    		return new ModelAndView(URLHelper.getURL(UserHelper.getLoginURL(request, response,"/user/search"),request), "userForm", new UserForm());
    	} else {
    		LOGGER.debug("Thyrsus will initiate a research : "+searchForm.getSearchString());
    		
    		
    		
    		ModelAndView mav = new ModelAndView (URLHelper.getURL("/home/home",request));
    		SessionHelper.setAttribute(request, Constants.TAB_INDEX,Constants.SEARCH_TAB_INDEX);
    		mav.addObject("searchForm", searchForm);
    		mav.addObject("searchResults",userService.searchUsers(searchForm.getSearchString()));
    		return mav;
    	}
	}
}
